package com.education.ai.controller;

import com.education.ai.entity.Class;
import com.education.ai.entity.Student;
import com.education.ai.entity.Teacher;
import com.education.ai.service.TeacherService;
import com.education.ai.util.ResponseResult;
import com.education.ai.util.PasswordUpdateUtil;
import com.education.ai.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.OutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Value("${default.password:88888888}")
    private String defaultPassword;

    @Autowired
    private PasswordUpdateUtil passwordUpdateUtil;

    @Autowired
    private StudentService studentService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private TeacherService teacherService;

    /**
     * 获取管理员仪表盘数据
     */
    @GetMapping("/dashboard")
    public ResponseEntity<?> getDashboardData() {
        try {
            logger.info("获取管理员仪表盘数据");
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            
            Map<String, Object> data = new HashMap<>();
            
            // 获取教师总数
            Integer teacherCount = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM teachers", Integer.class);
            data.put("teacherCount", teacherCount != null ? teacherCount : 0);
            
            // 获取学生总数
            Integer studentCount = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM students", Integer.class);
            data.put("studentCount", studentCount != null ? studentCount : 0);
            
            // 获取班级总数
            Integer classCount = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM classes", Integer.class);
            data.put("classCount", classCount != null ? classCount : 0);
            
            // 获取练习题总数
            Integer exerciseCount = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM exercises", Integer.class);
            data.put("exerciseCount", exerciseCount != null ? exerciseCount : 0);
            
            // 从数据库查询最近登录活动数据
            List<Map<String, Object>> recentActivities = new ArrayList<>();
            
            // 查询最近登录的教师
            String teacherLoginSql = 
                "SELECT name as user_name, 'teacher' as user_type, last_login_time " +
                "FROM teachers " +
                "WHERE last_login_time IS NOT NULL " +
                "ORDER BY last_login_time DESC " +
                "LIMIT 5";
            
            List<Map<String, Object>> teacherLogins = jdbcTemplate.queryForList(teacherLoginSql);
            
            // 查询最近登录的学生
            String studentLoginSql = 
                "SELECT name as user_name, 'student' as user_type, last_login_time " +
                "FROM students " +
                "WHERE last_login_time IS NOT NULL " +
                "ORDER BY last_login_time DESC " +
                "LIMIT 5";
            
            List<Map<String, Object>> studentLogins = jdbcTemplate.queryForList(studentLoginSql);
            
            // 查询最近登录的管理员
            String adminLoginSql = 
                "SELECT username as user_name, 'admin' as user_type, last_login_time " +
                "FROM admins " +
                "WHERE last_login_time IS NOT NULL " +
                "ORDER BY last_login_time DESC " +
                "LIMIT 5";
            
            List<Map<String, Object>> adminLogins = new ArrayList<>();
            try {
                adminLogins = jdbcTemplate.queryForList(adminLoginSql);
            } catch (Exception e) {
                // 如果管理员表不存在，忽略错误
                logger.warn("查询管理员登录记录失败: {}", e.getMessage());
            }
            
            // 合并所有登录记录
            recentActivities.addAll(teacherLogins);
            recentActivities.addAll(studentLogins);
            recentActivities.addAll(adminLogins);
            
            // 按登录时间降序排序，取前5条
            recentActivities.sort((a, b) -> {
                Object timeA = a.get("last_login_time");
                Object timeB = b.get("last_login_time");
                if (timeA == null) return 1;
                if (timeB == null) return -1;
                return ((Comparable) timeB).compareTo(timeA);
            });
            
            // 只保留前5条记录
            if (recentActivities.size() > 5) {
                recentActivities = recentActivities.subList(0, 5);
            }
            
            // 格式化数据以匹配前端期望的格式
            List<Map<String, Object>> formattedActivities = new ArrayList<>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            
            for (Map<String, Object> activity : recentActivities) {
                Map<String, Object> formattedActivity = new HashMap<>();
                
                // 提取并格式化用户名
                Object userNameObj = activity.get("user_name");
                String userName = (userNameObj != null) ? userNameObj.toString() : "未知用户";
                formattedActivity.put("userName", userName);
                
                // 提取并格式化用户类型
                Object userTypeObj = activity.get("user_type");
                String userType = (userTypeObj != null) ? userTypeObj.toString() : "未知";
                // 将英文用户类型转换为中文
                switch (userType) {
                    case "teacher":
                        formattedActivity.put("userType", "教师");
                        break;
                    case "student":
                        formattedActivity.put("userType", "学生");
                        break;
                    case "admin":
                        formattedActivity.put("userType", "管理员");
                        break;
                    default:
                        formattedActivity.put("userType", userType);
                }
                
                // 提取并格式化登录时间
                Object loginTimeObj = activity.get("last_login_time");
                if (loginTimeObj != null) {
                    // 处理不同类型的时间对象
                    String loginTime;
                    if (loginTimeObj instanceof java.sql.Timestamp) {
                        LocalDateTime ldt = ((java.sql.Timestamp) loginTimeObj).toLocalDateTime();
                        loginTime = ldt.format(formatter);
                    } else if (loginTimeObj instanceof LocalDateTime) {
                        loginTime = ((LocalDateTime) loginTimeObj).format(formatter);
                    } else {
                        loginTime = loginTimeObj.toString();
                    }
                    formattedActivity.put("loginTime", loginTime);
                } else {
                    formattedActivity.put("loginTime", "未知时间");
                }
                
                formattedActivities.add(formattedActivity);
            }
            
            // 如果没有记录，添加一条默认信息
            if (formattedActivities.isEmpty()) {
                Map<String, Object> defaultActivity = new HashMap<>();
                defaultActivity.put("userName", "系统");
                defaultActivity.put("userType", "系统");
                defaultActivity.put("loginTime", LocalDateTime.now().format(formatter));
                formattedActivities.add(defaultActivity);
            }
            
            data.put("recentActivities", formattedActivities);
            
            result.put("data", data);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取管理员仪表盘数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取管理员仪表盘数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 重置所有用户密码
     */
    @PostMapping("/reset-all-passwords")
    public ResponseEntity<?> resetAllPasswords(
            @RequestParam(defaultValue = "88888888") String password) {
        
        logger.info("执行所有用户密码重置操作，新密码: {}", password);
        boolean success = passwordUpdateUtil.resetAllPasswords(password);
        
        if (success) {
            return ResponseEntity.ok(ResponseResult.success("所有用户密码已重置为: " + password));
        } else {
            return ResponseEntity.internalServerError().body(
                    ResponseResult.error("密码重置失败，请查看服务器日志"));
        }
    }

    /**
     * 获取学生的学习进度和表现
     */
    @GetMapping("/student/learning-progress/{studentId}")
    public ResponseEntity<?> getStudentLearningProgress(@PathVariable String studentId) {
        try {
            logger.info("管理员请求获取学生[{}]的学习进度数据", studentId);
            Map<String, Object> progressData = studentService.getStudentLearningProgress(studentId);
            return ResponseEntity.ok(progressData);
        } catch (Exception e) {
            logger.error("获取学生学习进度失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取学生学习进度失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取班级学习进度概览
     */
    @GetMapping("/class/learning-progress/{classId}")
    public ResponseEntity<?> getClassLearningProgress(@PathVariable String classId) {
        try {
            logger.info("管理员请求获取班级[{}]的学习进度概览", classId);
            
            Map<String, Object> result = new HashMap<>();
            
            // 查询班级学习进度统计数据
            String sql = "SELECT s.student_id, s.name, " +
                    "AVG(CASE WHEN sps.correct_count IS NOT NULL THEN (sps.correct_count * 100.0 / NULLIF(sps.question_count, 0)) ELSE 0 END) as avg_progress " +
                    "FROM students s " +
                    "LEFT JOIN student_practice_sessions sps ON s.student_id = sps.student_id " +
                    "WHERE s.class_id = ? " +
                    "GROUP BY s.student_id, s.name";
            
            List<Map<String, Object>> studentProgress = jdbcTemplate.queryForList(sql, classId);
            
            // 计算班级整体学习进度
            double classAvgProgress = 0;
            if (!studentProgress.isEmpty()) {
                double totalProgress = 0;
                for (Map<String, Object> student : studentProgress) {
                    Object progressObj = student.get("avg_progress");
                    if (progressObj != null) {
                        if (progressObj instanceof BigDecimal) {
                            totalProgress += ((BigDecimal) progressObj).doubleValue();
                        } else if (progressObj instanceof Double) {
                            totalProgress += (Double) progressObj;
                        } else {
                            totalProgress += Double.parseDouble(progressObj.toString());
                        }
                    }
                }
                classAvgProgress = totalProgress / studentProgress.size();
            }
            
            // 查询班级学科进度数据
            String subjectSql = "SELECT sps.subject, " +
                    "AVG(CASE WHEN sps.correct_count IS NOT NULL THEN (sps.correct_count * 100.0 / NULLIF(sps.question_count, 0)) ELSE 0 END) as subject_progress " +
                    "FROM students s " +
                    "JOIN student_practice_sessions sps ON s.student_id = sps.student_id " +
                    "WHERE s.class_id = ? " +
                    "GROUP BY sps.subject";
            
            List<Map<String, Object>> subjectProgress = jdbcTemplate.queryForList(subjectSql, classId);
            
            // 将学科英文代码转换为中文名称
            for (Map<String, Object> subject : subjectProgress) {
                String subjectCode = (String) subject.get("subject");
                String subjectName = convertSubjectCodeToChinese(subjectCode);
                subject.put("subject", subjectName);
            }
            
            // 统计练习次数和题目数据
            String statsSql = "SELECT COUNT(DISTINCT sps.id) as total_sessions, " +
                    "SUM(sps.question_count) as total_questions, " +
                    "SUM(sps.correct_count) as correct_questions " +
                    "FROM students s " +
                    "JOIN student_practice_sessions sps ON s.student_id = sps.student_id " +
                    "WHERE s.class_id = ?";
            
            Map<String, Object> practiceStats = jdbcTemplate.queryForMap(statsSql, classId);
            
            result.put("success", true);
            result.put("classId", classId);
            result.put("averageProgress", Math.round(classAvgProgress));
            result.put("studentProgress", studentProgress);
            result.put("subjectProgress", subjectProgress);
            result.put("practiceStats", practiceStats);
            result.put("message", "成功获取班级学习进度概览");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取班级学习进度概览失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取班级学习进度概览失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取班级所有学生的科目进度数据
     */
    @GetMapping("/class/subject-progress/{classId}/{subject}")
    public ResponseEntity<?> getClassSubjectProgress(
            @PathVariable String classId,
            @PathVariable String subject) {
        try {
            logger.info("管理员请求获取班级[{}]学科[{}]的学习进度数据", classId, subject);
            
            // 将前端传来的中文学科名称转换为英文代码
            String subjectCode = convertSubjectToCode(subject);
            logger.info("转换学科名称: {} -> {}", subject, subjectCode);
            
            // 查询班级内所有学生该学科的学习进度
            String sql = "SELECT s.student_id, s.name, " +
                    "COALESCE(SUM(sps.correct_count) * 100.0 / NULLIF(SUM(sps.question_count), 0), 0) as progress, " +
                    "COUNT(DISTINCT sps.id) as session_count, " +
                    "SUM(sps.question_count) as total_questions, " +
                    "SUM(sps.correct_count) as correct_questions, " +
                    "COALESCE(SUM(sps.correct_count) * 100.0 / NULLIF(SUM(sps.question_count), 0), 0) as accuracy " +
                    "FROM students s " +
                    "LEFT JOIN student_practice_sessions sps ON s.student_id = sps.student_id AND sps.subject = ? " +
                    "WHERE s.class_id = ? " +
                    "GROUP BY s.student_id, s.name " +
                    "ORDER BY progress DESC";
            
            List<Map<String, Object>> studentSubjectProgress = jdbcTemplate.queryForList(sql, subjectCode, classId);
            
            // 获取该学科的知识点掌握情况
            List<Map<String, Object>> knowledgePointMastery = new ArrayList<>();
            try {
                String knowledgePointSql = "SELECT kp.knowledge_point, " +
                        "AVG(CASE WHEN spd.is_correct THEN 100 ELSE 0 END) as mastery " +
                        "FROM students s " +
                        "JOIN student_practice_sessions sps ON s.student_id = sps.student_id " +
                        "JOIN student_practice_details spd ON sps.id = spd.session_id " +
                        "JOIN knowledge_points kp ON spd.knowledge_point_id = kp.id " +
                        "WHERE s.class_id = ? AND sps.subject = ? " +
                        "GROUP BY kp.knowledge_point " +
                        "ORDER BY mastery DESC";
                
                knowledgePointMastery = jdbcTemplate.queryForList(knowledgePointSql, classId, subjectCode);
            } catch (Exception e) {
                logger.warn("获取知识点掌握情况失败，可能是相关表不存在: {}", e.getMessage());
                // 如果表不存在，使用简化的查询
                try {
                    // 备用查询：使用练习详情表的直接统计
                    String fallbackSql = "SELECT question_type as knowledge_point, " +
                            "AVG(CASE WHEN is_correct THEN 100 ELSE 0 END) as mastery " +
                            "FROM student_practice_details spd " +
                            "JOIN student_practice_sessions sps ON spd.session_id = sps.id " +
                            "JOIN students s ON sps.student_id = s.student_id " +
                            "WHERE s.class_id = ? AND sps.subject = ? " +
                            "GROUP BY question_type " +
                            "ORDER BY mastery DESC";
                    
                    knowledgePointMastery = jdbcTemplate.queryForList(fallbackSql, classId, subjectCode);
                } catch (Exception ex) {
                    logger.warn("备用知识点查询也失败了: {}", ex.getMessage());
                    // 忽略，保留空列表
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("classId", classId);
            result.put("subject", subject);
            result.put("studentProgress", studentSubjectProgress);
            result.put("knowledgePoints", knowledgePointMastery);
            result.put("message", "成功获取班级学科进度数据");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取班级学科进度数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取班级学科进度数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取所有教师列表（分页）
     */
    @GetMapping("/teachers")
    public ResponseEntity<?> getAllTeachers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String query) {
        try {
            logger.info("获取教师列表: page={}, size={}, query={}", page, size, query);
            
            List<Teacher> teachers;
            int totalTeachers;
            
            if (query != null && !query.trim().isEmpty()) {
                // 如果有查询条件，执行搜索
                teachers = teacherService.searchTeachersByName(query);
                totalTeachers = teachers.size();
                
                // 手动分页 (简化处理)
                int fromIndex = (page - 1) * size;
                int toIndex = Math.min(fromIndex + size, teachers.size());
                
                if (fromIndex < teachers.size()) {
                    teachers = teachers.subList(fromIndex, toIndex);
                } else {
                    teachers = new ArrayList<>();
                }
            } else {
                // 获取所有教师
                teachers = teacherService.getAllTeachers();
                totalTeachers = teachers.size();
                
                // 手动分页 (简化处理)
                int fromIndex = (page - 1) * size;
                int toIndex = Math.min(fromIndex + size, teachers.size());
                
                if (fromIndex < teachers.size()) {
                    teachers = teachers.subList(fromIndex, toIndex);
                } else {
                    teachers = new ArrayList<>();
                }
            }
            
            // 构建与前端期望格式匹配的响应
            Map<String, Object> pageData = new HashMap<>();
            pageData.put("records", teachers);
            pageData.put("total", totalTeachers);
            pageData.put("current", page);
            pageData.put("size", size);
            pageData.put("pages", (int) Math.ceil((double) totalTeachers / size));
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", pageData);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取教师列表失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取教师列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 根据ID获取教师
     */
    @GetMapping("/teacher/{id}")
    public ResponseEntity<?> getTeacherById(@PathVariable Long id) {
        try {
            logger.info("获取教师信息: id={}", id);
            
            Optional<Teacher> teacherOpt = teacherService.getTeacherById(id);
            
            if (teacherOpt.isPresent()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", teacherOpt.get());
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的教师");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (Exception e) {
            logger.error("获取教师信息失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取教师信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 创建教师
     */
    @PostMapping("/teacher")
    public ResponseEntity<?> createTeacher(@RequestBody Teacher teacher) {
        try {
            logger.info("创建教师: {}", teacher);
            
            // 如果教师工号为空，自动生成工号
            if (teacher.getTeacherId() == null || teacher.getTeacherId().isEmpty()) {
                // 生成格式为: 8位数字组成的工号
                String newTeacherId = generateTeacherId();
                teacher.setTeacherId(newTeacherId);
                logger.info("自动生成教师工号: {}", newTeacherId);
            }
            
            // 检查密码是否为空，若为空设置默认密码
            if (teacher.getPassword() == null || teacher.getPassword().isEmpty()) {
                // 使用配置文件中的默认密码
                teacher.setPassword(defaultPassword);
                logger.info("使用默认密码");
            }
            
            // 检查教师工号是否已存在
            if (teacherService.isTeacherIdExists(teacher.getTeacherId())) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "教师工号已存在");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 确保新创建的教师lastLoginTime为null而不是空字符串
            teacher.setLastLoginTime(null);
            
            Teacher createdTeacher = teacherService.saveTeacher(teacher);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", createdTeacher);
            result.put("message", "教师创建成功");
            
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (Exception e) {
            logger.error("创建教师失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "创建教师失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 生成新的教师工号
     */
    private String generateTeacherId() {
        // 获取当前最大的教师工号
        String maxTeacherId = teacherService.getMaxTeacherId();
        
        // 如果没有现有教师，从基础号码开始
        if (maxTeacherId == null || maxTeacherId.isEmpty()) {
            return "88000001";
        }
        
        try {
            // 尝试解析为数字并加1
            int numericId = Integer.parseInt(maxTeacherId);
            return String.format("%08d", numericId + 1);
        } catch (NumberFormatException e) {
            // 如果解析失败，使用时间戳作为备用方案
            return "88" + String.format("%06d", (int)(Math.random() * 1000000));
        }
    }
    
    /**
     * 更新教师
     */
    @PutMapping("/teacher/{id}")
    public ResponseEntity<?> updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
        try {
            logger.info("更新教师: id={}, teacher={}", id, teacher);
            
            Optional<Teacher> existingTeacherOpt = teacherService.getTeacherById(id);
            
            if (!existingTeacherOpt.isPresent()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的教师");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            Teacher existingTeacher = existingTeacherOpt.get();
            
            // 检查如果工号变更，确认新工号不存在
            if (teacher.getTeacherId() != null && !teacher.getTeacherId().isEmpty() &&
                    !existingTeacher.getTeacherId().equals(teacher.getTeacherId()) && 
                    teacherService.isTeacherIdExists(teacher.getTeacherId())) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "教师工号已存在");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 设置ID确保更新而不是创建新记录
            teacher.setId(id);
            
            // 确保lastLoginTime字段不是空字符串
            if (teacher.getLastLoginTime() != null && teacher.getLastLoginTime().toString().isEmpty()) {
                teacher.setLastLoginTime(null);
            }
            
            Teacher updatedTeacher = teacherService.saveTeacher(teacher);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", updatedTeacher);
            result.put("message", "教师更新成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("更新教师失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新教师失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 删除教师
     */
    @DeleteMapping("/teacher/{id}")
    public ResponseEntity<?> deleteTeacher(@PathVariable Long id) {
        try {
            logger.info("删除教师: id={}", id);
            
            Optional<Teacher> teacherOpt = teacherService.getTeacherById(id);
            
            if (!teacherOpt.isPresent()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的教师");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            teacherService.deleteTeacher(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "教师删除成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除教师失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "删除教师失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取所有学生列表（分页）
     */
    @GetMapping("/students")
    public ResponseEntity<?> getAllStudents(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String query,
            @RequestParam(required = false) String classId) {
        try {
            logger.info("获取学生列表: page={}, size={}, query={}, classId={}", page, size, query, classId);
            
            List<Student> students;
            int totalStudents;
            
            if (classId != null && !classId.trim().isEmpty()) {
                // 根据班级ID查询学生
                String classNameSql = "SELECT class_name FROM classes WHERE id = ?";
                String className = jdbcTemplate.queryForObject(classNameSql, String.class, classId);
                
                if (className != null) {
                    // 使用班级名称查询学生
                    String sql = "SELECT * FROM students WHERE class_name = ?";
                    students = jdbcTemplate.query(sql, 
                        new Object[]{className}, 
                        (rs, rowNum) -> {
                            Student student = new Student();
                            student.setId(rs.getLong("id"));
                            student.setName(rs.getString("name"));
                            student.setStudentId(rs.getString("student_id"));
                            student.setGrade(rs.getString("grade"));
                            student.setClassId(rs.getString("class_id"));
                            student.setClassName(rs.getString("class_name"));
                            student.setEmail(rs.getString("email"));
                            student.setPhone(rs.getString("phone"));
                            student.setStatus(rs.getInt("status"));
                            return student;
                        });
                    totalStudents = students.size();
                } else {
                    students = new ArrayList<>();
                    totalStudents = 0;
                }
            } else if (query != null && !query.trim().isEmpty()) {
                // 根据姓名或学号查询学生
                String sql = "SELECT * FROM students WHERE name LIKE ? OR student_id LIKE ?";
                students = jdbcTemplate.query(sql, 
                    new Object[]{"%" + query + "%", "%" + query + "%"}, 
                    (rs, rowNum) -> {
                        Student student = new Student();
                        student.setId(rs.getLong("id"));
                        student.setName(rs.getString("name"));
                        student.setStudentId(rs.getString("student_id"));
                        student.setGrade(rs.getString("grade"));
                        student.setClassId(rs.getString("class_id"));
                        student.setClassName(rs.getString("class_name"));
                        student.setEmail(rs.getString("email"));
                        student.setPhone(rs.getString("phone"));
                        student.setStatus(rs.getInt("status"));
                        return student;
                    });
                totalStudents = students.size();
            } else {
                // 获取所有学生
                String sql = "SELECT * FROM students";
                students = jdbcTemplate.query(sql, 
                    (rs, rowNum) -> {
                        Student student = new Student();
                        student.setId(rs.getLong("id"));
                        student.setName(rs.getString("name"));
                        student.setStudentId(rs.getString("student_id"));
                        student.setGrade(rs.getString("grade"));
                        student.setClassId(rs.getString("class_id"));
                        student.setClassName(rs.getString("class_name"));
                        student.setEmail(rs.getString("email"));
                        student.setPhone(rs.getString("phone"));
                        student.setStatus(rs.getInt("status"));
                        return student;
                    });
                totalStudents = students.size();
            }
            
            // 手动分页
            int fromIndex = (page - 1) * size;
            int toIndex = Math.min(fromIndex + size, students.size());
            final List<Student> pagedStudents;
            if (fromIndex < students.size()) {
                pagedStudents = students.subList(fromIndex, toIndex);
            } else {
                pagedStudents = new ArrayList<>();
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", new HashMap<String, Object>() {{
                put("records", pagedStudents);
                put("total", totalStudents);
                put("size", size);
                put("current", page);
            }});
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取学生列表失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取学生列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 根据ID获取学生
     */
    @GetMapping("/student/{id}")
    public ResponseEntity<?> getStudentById(@PathVariable Long id) {
        try {
            logger.info("获取学生信息: id={}", id);
            
            Student student = studentService.findById(id);
            
            if (student != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", student);
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的学生");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (Exception e) {
            logger.error("获取学生信息失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取学生信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 创建学生
     */
    @PostMapping("/student")
    public ResponseEntity<?> createStudent(@RequestBody Student student) {
        try {
            logger.info("创建学生: {}", student);
            
            // 检查学生学号是否已存在
            String checkSql = "SELECT COUNT(*) FROM students WHERE student_id = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, student.getStudentId());
            
            if (count != null && count > 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "学生学号已存在");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            student.setCreateTime(now);
            student.setUpdateTime(now);
            
            Student createdStudent = studentService.save(student);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", createdStudent);
            result.put("message", "学生创建成功");
            
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (Exception e) {
            logger.error("创建学生失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "创建学生失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 更新学生信息
     */
    @PutMapping("/student/{id}")
    public ResponseEntity<?> updateStudent(@PathVariable Long id, @RequestBody Student student) {
        try {
            logger.info("更新学生: id={}, student={}", id, student);
            
            // 获取当前学生信息
            Student existingStudent = studentService.findById(id);
            
            if (existingStudent == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的学生");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 检查如果学号变更，确认新学号不存在
            if (student.getStudentId() != null && !student.getStudentId().isEmpty() &&
                    !existingStudent.getStudentId().equals(student.getStudentId())) {
                
                // 检查新学号是否已存在
                String checkSql = "SELECT COUNT(*) FROM students WHERE student_id = ?";
                Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, student.getStudentId());
                
                if (count != null && count > 0) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "学生学号已存在");
                    return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
                }
            }
            
            // 设置ID确保更新而不是创建新记录
            student.setId(id);
            
            // 保留密码，避免被更新为空值
            if (student.getPassword() == null || student.getPassword().isEmpty()) {
                student.setPassword(existingStudent.getPassword());
            }
            
            // 确保lastLoginTime字段不是空字符串
            if (student.getLastLoginTime() != null && student.getLastLoginTime().toString().isEmpty()) {
                student.setLastLoginTime(null);
            }
            
            // 更新学生信息
            Student updatedStudent = studentService.save(student);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", updatedStudent);
            result.put("message", "学生更新成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("更新学生失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新学生失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 重置学生密码
     */
    @PostMapping("/student/{id}/reset-password")
    public ResponseEntity<?> resetStudentPassword(@PathVariable Long id) {
        try {
            logger.info("重置学生密码: id={}", id);
            
            // 获取当前学生信息
            Student student = studentService.findById(id);
            
            if (student == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的学生");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 重置为默认密码
            student.setPassword(defaultPassword);
            
            // 更新学生信息
            studentService.save(student);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "学生密码重置成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("重置学生密码失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "重置学生密码失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 删除学生
     */
    @DeleteMapping("/student/{id}")
    public ResponseEntity<?> deleteStudent(@PathVariable Long id) {
        try {
            logger.info("删除学生: id={}", id);
            
            // 检查学生是否存在
            Student student = studentService.findById(id);
            
            if (student == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的学生");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 删除学生
            studentService.deleteById(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "学生删除成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除学生失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "删除学生失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 批量重置学生密码
     */
    @PostMapping("/students/reset-password")
    public ResponseEntity<?> resetStudentsPassword(@RequestBody Map<String, Object> requestBody) {
        try {
            List<?> studentIdObjects = (List<?>) requestBody.get("studentIds");
            String password = requestBody.get("password") != null ? requestBody.get("password").toString() : null;
            
            if (studentIdObjects == null || studentIdObjects.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未选择学生");
                return ResponseEntity.badRequest().body(result);
            }
            
            logger.info("批量重置学生密码: studentIds={}, 使用{}密码", studentIdObjects, password == null ? "默认" : "指定");
            
            // 如果未指定密码，使用默认密码
            if (password == null || password.isEmpty()) {
                password = defaultPassword;
            }
            
            int successCount = 0;
            for (Object idObject : studentIdObjects) {
                try {
                    // 安全地将任何数字类型转换为Long
                    Long studentId;
                    if (idObject instanceof Integer) {
                        studentId = ((Integer) idObject).longValue();
                    } else if (idObject instanceof Long) {
                        studentId = (Long) idObject;
                    } else if (idObject instanceof Number) {
                        studentId = ((Number) idObject).longValue();
                    } else {
                        studentId = Long.parseLong(idObject.toString());
                    }
                    
                    Student student = studentService.findById(studentId);
                    if (student != null) {
                        student.setPassword(password);
                        studentService.save(student);
                        successCount++;
                    }
                } catch (Exception e) {
                    logger.error("重置学生[{}]密码失败: {}", idObject, e.getMessage());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            if (successCount == studentIdObjects.size()) {
                result.put("success", true);
                result.put("message", "成功重置 " + successCount + " 名学生的密码");
            } else if (successCount > 0) {
                result.put("success", true);
                result.put("message", "部分重置成功: " + successCount + "/" + studentIdObjects.size());
            } else {
                result.put("success", false);
                result.put("message", "重置密码失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("批量重置学生密码失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量重置密码失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 批量删除学生
     */
    @PostMapping("/students/batch-delete")
    public ResponseEntity<?> batchDeleteStudents(@RequestBody Map<String, Object> requestBody) {
        try {
            List<?> studentIdObjects = (List<?>) requestBody.get("studentIds");
            
            if (studentIdObjects == null || studentIdObjects.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未选择学生");
                return ResponseEntity.badRequest().body(result);
            }
            
            logger.info("批量删除学生: studentIds={}", studentIdObjects);
            
            int successCount = 0;
            List<Map<String, Object>> failList = new ArrayList<>();
            
            for (Object idObject : studentIdObjects) {
                try {
                    // 安全地将任何数字类型转换为Long
                    Long studentId;
                    if (idObject instanceof Integer) {
                        studentId = ((Integer) idObject).longValue();
                    } else if (idObject instanceof Long) {
                        studentId = (Long) idObject;
                    } else if (idObject instanceof Number) {
                        studentId = ((Number) idObject).longValue();
                    } else {
                        studentId = Long.parseLong(idObject.toString());
                    }
                    
                    Student student = studentService.findById(studentId);
                    if (student != null) {
                        studentService.deleteById(studentId);
                        successCount++;
                    } else {
                        Map<String, Object> failInfo = new HashMap<>();
                        failInfo.put("id", studentId);
                        failInfo.put("reason", "未找到学生");
                        failList.add(failInfo);
                    }
                } catch (Exception e) {
                    logger.error("删除学生[{}]失败: {}", idObject, e.getMessage());
                    Map<String, Object> failInfo = new HashMap<>();
                    failInfo.put("id", idObject);
                    failInfo.put("reason", e.getMessage());
                    failList.add(failInfo);
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            if (successCount == studentIdObjects.size()) {
                result.put("success", true);
                result.put("message", "成功删除 " + successCount + " 名学生");
            } else if (successCount > 0) {
                result.put("success", true);
                result.put("message", "部分删除成功: " + successCount + "/" + studentIdObjects.size());
                result.put("failList", failList);
            } else {
                result.put("success", false);
                result.put("message", "删除学生失败");
                result.put("failList", failList);
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("批量删除学生失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 导出学生数据
     */
    @GetMapping("/students/export")
    public void exportStudents(
            @RequestParam(required = false) String query,
            @RequestParam(required = false) String classId,
            HttpServletResponse response) {
        
        try {
            logger.info("导出学生数据: query={}, classId={}", query, classId);
            
            List<Student> students;
            
            if (classId != null && !classId.trim().isEmpty()) {
                // 根据班级ID查询学生
                students = studentService.findByClassId(classId);
            } else if (query != null && !query.trim().isEmpty()) {
                // 根据姓名或学号查询学生
                String sql = "SELECT * FROM students WHERE name LIKE ? OR student_id LIKE ?";
                students = jdbcTemplate.query(sql, 
                    new Object[]{"%" + query + "%", "%" + query + "%"}, 
                    (rs, rowNum) -> {
                        Student student = new Student();
                        student.setId(rs.getLong("id"));
                        student.setName(rs.getString("name"));
                        student.setStudentId(rs.getString("student_id"));
                        student.setGrade(rs.getString("grade"));
                        student.setClassId(rs.getString("class_id"));
                        student.setClassName(rs.getString("class_name"));
                        student.setEmail(rs.getString("email"));
                        student.setPhone(rs.getString("phone"));
                        student.setStatus(rs.getInt("status"));
                        // 其他字段...
                        return student;
                    });
            } else {
                // 获取所有学生
                students = studentService.findAll();
            }
            
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("学生数据_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            
            // 创建工作簿和工作表
            try (OutputStream os = response.getOutputStream()) {
                // 这里应该使用Excel库如POI导出数据
                // 由于是示例，我们不实现具体的导出逻辑
                logger.info("已导出 {} 条学生数据", students.size());
                os.write("学生数据导出示例".getBytes(StandardCharsets.UTF_8));
            }
            
        } catch (Exception e) {
            logger.error("导出学生数据失败: {}", e.getMessage(), e);
            // 导出失败时，设置错误响应
            try {
                response.setContentType("application/json");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("{\"success\": false, \"message\": \"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ex) {
                logger.error("写入错误响应失败", ex);
            }
        }
    }
    
    /**
     * 获取学生考试记录
     */
    @GetMapping("/student/{id}/exam-records")
    public ResponseEntity<?> getStudentExamRecords(@PathVariable Long id) {
        try {
            logger.info("获取学生考试记录: id={}", id);
            
            // 获取学生信息
            Student student = studentService.findById(id);
            
            if (student == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的学生");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 查询学生的考试记录
            String sql = "SELECT * FROM exam_records WHERE student_id = ? ORDER BY exam_time DESC";
            
            List<Map<String, Object>> examRecords = jdbcTemplate.queryForList(sql, student.getStudentId());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", examRecords);
            result.put("message", "获取考试记录成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取学生考试记录失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取考试记录失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 获取所有班级列表
     */
    @GetMapping("/classes")
    public ResponseEntity<?> getAllClasses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String query) {
        try {
            logger.info("获取班级列表: page={}, size={}, query={}", page, size, query);
            
            List<Map<String, Object>> classes;
            int totalClasses;
            
            if (query != null && !query.trim().isEmpty()) {
                // 根据班级名称查询
                String sql = "SELECT c.id, c.class_name as className, c.grade as gradeLevel, " +
                             "COUNT(s.id) as studentCount, " +
                             "IFNULL(c.chinese, '待分配') as chineseTeacher, " +
                             "IFNULL(c.math, '待分配') as mathTeacher, " +
                             "IFNULL(c.english, '待分配') as englishTeacher, " +
                             "IFNULL(c.physics, '待分配') as physicsTeacher, " +
                             "IFNULL(c.chemistry, '待分配') as chemistryTeacher, " +
                             "IFNULL(c.biology, '待分配') as biologyTeacher, " +
                             "IFNULL(c.politics, '待分配') as politicsTeacher, " +
                             "IFNULL(c.history, '待分配') as historyTeacher, " +
                             "IFNULL(c.geography, '待分配') as geographyTeacher " +
                             "FROM classes c " +
                             "LEFT JOIN students s ON c.class_name = s.class_name " +
                             "WHERE c.class_name LIKE ? " +
                             "GROUP BY c.id";
                classes = jdbcTemplate.queryForList(sql, "%" + query + "%");
                totalClasses = classes.size();
            } else {
                // 获取所有班级并统计每个班级的学生数量
                String sql = "SELECT c.id, c.class_name as className, c.grade as gradeLevel, " +
                             "COUNT(s.id) as studentCount, " +
                             "IFNULL(c.chinese, '待分配') as chineseTeacher, " +
                             "IFNULL(c.math, '待分配') as mathTeacher, " +
                             "IFNULL(c.english, '待分配') as englishTeacher, " +
                             "IFNULL(c.physics, '待分配') as physicsTeacher, " +
                             "IFNULL(c.chemistry, '待分配') as chemistryTeacher, " +
                             "IFNULL(c.biology, '待分配') as biologyTeacher, " +
                             "IFNULL(c.politics, '待分配') as politicsTeacher, " +
                             "IFNULL(c.history, '待分配') as historyTeacher, " +
                             "IFNULL(c.geography, '待分配') as geographyTeacher " +
                             "FROM classes c " +
                             "LEFT JOIN students s ON c.class_name = s.class_name " +
                             "GROUP BY c.id";
                classes = jdbcTemplate.queryForList(sql);
                totalClasses = classes.size();
            }
            
            // 手动分页 (简化处理)
            int fromIndex = (page - 1) * size;
            int toIndex = Math.min(fromIndex + size, classes.size());
            
            if (fromIndex < classes.size()) {
                classes = classes.subList(fromIndex, toIndex);
            } else {
                classes = new ArrayList<>();
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", classes);
            result.put("total", totalClasses);
            result.put("page", page);
            result.put("size", size);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取班级列表失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取班级列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 根据ID获取班级
     */
    @GetMapping("/class/{id}")
    public ResponseEntity<?> getClassById(@PathVariable Long id) {
        try {
            logger.info("获取班级信息: id={}", id);
            
            // 查询班级基本信息
            String classSql = "SELECT id, class_name as className, grade as gradeLevel, " +
                              "IFNULL(chinese, '待分配') as chineseTeacher, " +
                              "IFNULL(math, '待分配') as mathTeacher, " +
                              "IFNULL(english, '待分配') as englishTeacher, " +
                              "IFNULL(physics, '待分配') as physicsTeacher, " +
                              "IFNULL(chemistry, '待分配') as chemistryTeacher, " +
                              "IFNULL(biology, '待分配') as biologyTeacher, " +
                              "IFNULL(politics, '待分配') as politicsTeacher, " +
                              "IFNULL(history, '待分配') as historyTeacher, " +
                              "IFNULL(geography, '待分配') as geographyTeacher " +
                              "FROM classes WHERE id = ?";
            List<Map<String, Object>> classResults = jdbcTemplate.queryForList(classSql, id);
            
            if (classResults.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的班级");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            Map<String, Object> classData = classResults.get(0);
            
            // 查询班级中的学生数量
            String countSql = "SELECT COUNT(*) FROM students WHERE class_name = (SELECT class_name FROM classes WHERE id = ?)";
            Integer studentCount = jdbcTemplate.queryForObject(countSql, Integer.class, id);
            classData.put("studentCount", studentCount != null ? studentCount : 0);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", classData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取班级信息失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取班级信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 创建班级
     */
    @PostMapping("/class")
    public ResponseEntity<?> createClass(@RequestBody Class classObj) {
        try {
            logger.info("创建班级: {}", classObj);
            
            // 检查班级名称是否已存在
            String checkSql = "SELECT COUNT(*) FROM classes WHERE class_name = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, classObj.getClassName());
            
            if (count != null && count > 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "班级名称已存在");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 设置创建时间
            if (classObj.getCreateTime() == null) {
                classObj.setCreateTime(new Date());
            }
            classObj.setUpdateTime(new Date());
            
            // 保存班级信息
            String insertSql = "INSERT INTO classes (class_name, grade, chinese, math, english, physics, " +
                              "chemistry, biology, politics, history, geography, create_time, update_time) " +
                              "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(insertSql, 
                    classObj.getClassName(), 
                    classObj.getGrade(),
                    classObj.getChinese(),
                    classObj.getMath(),
                    classObj.getEnglish(),
                    classObj.getPhysics(),
                    classObj.getChemistry(),
                    classObj.getBiology(),
                    classObj.getPolitics(),
                    classObj.getHistory(),
                    classObj.getGeography(), 
                    classObj.getCreateTime(), 
                    classObj.getUpdateTime());
            
            // 获取新创建的班级ID
            String idSql = "SELECT id FROM classes WHERE class_name = ? ORDER BY id DESC LIMIT 1";
            Long newId = jdbcTemplate.queryForObject(idSql, Long.class, classObj.getClassName());
            classObj.setId(newId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            
            // 查询更新后的最新班级数据
            String classSql = "SELECT id, class_name as className, grade as gradeLevel, " +
                             "IFNULL(chinese, '待分配') as chineseTeacher, " +
                             "IFNULL(math, '待分配') as mathTeacher, " +
                             "IFNULL(english, '待分配') as englishTeacher, " +
                             "IFNULL(physics, '待分配') as physicsTeacher, " +
                             "IFNULL(chemistry, '待分配') as chemistryTeacher, " +
                             "IFNULL(biology, '待分配') as biologyTeacher, " +
                             "IFNULL(politics, '待分配') as politicsTeacher, " +
                             "IFNULL(history, '待分配') as historyTeacher, " +
                             "IFNULL(geography, '待分配') as geographyTeacher " +
                             "FROM classes WHERE id = ?";
            List<Map<String, Object>> classResults = jdbcTemplate.queryForList(classSql, newId);
            Map<String, Object> classData = classResults.get(0);
            classData.put("studentCount", 0); // 新创建的班级没有学生
            
            result.put("data", classData);
            result.put("message", "班级创建成功");
            
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (Exception e) {
            logger.error("创建班级失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "创建班级失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 更新班级
     */
    @PutMapping("/class/{id}")
    public ResponseEntity<?> updateClass(@PathVariable Long id, @RequestBody Class classObj) {
        try {
            logger.info("更新班级: id={}, class={}", id, classObj);
            
            // 检查班级是否存在
            String checkExistsSql = "SELECT COUNT(*) FROM classes WHERE id = ?";
            Integer existsCount = jdbcTemplate.queryForObject(checkExistsSql, Integer.class, id);
            
            if (existsCount == null || existsCount == 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的班级");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 检查班级名称是否已被其他班级使用
            String checkNameSql = "SELECT COUNT(*) FROM classes WHERE class_name = ? AND id != ?";
            Integer nameCount = jdbcTemplate.queryForObject(checkNameSql, Integer.class, classObj.getClassName(), id);
            
            if (nameCount != null && nameCount > 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "班级名称已存在");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 设置更新时间
            classObj.setUpdateTime(new Date());
            
            // 更新班级信息 - 添加日志检查grade字段
            logger.info("更新班级 - grade字段值: {}", classObj.getGrade());
            
            // 确保grade字段不为空
            if (classObj.getGrade() == null) {
                classObj.setGrade("高一"); // 设置默认值
                logger.warn("班级年级为null，设置默认值为'高一'");
            }
            
            String updateSql = "UPDATE classes SET class_name = ?, grade = ?, " +
                              "chinese = ?, math = ?, english = ?, physics = ?, " +
                              "chemistry = ?, biology = ?, politics = ?, history = ?, " +
                              "geography = ?, update_time = ? WHERE id = ?";
            jdbcTemplate.update(updateSql, 
                    classObj.getClassName(), 
                    classObj.getGrade(), 
                    classObj.getChinese(),
                    classObj.getMath(),
                    classObj.getEnglish(),
                    classObj.getPhysics(),
                    classObj.getChemistry(),
                    classObj.getBiology(),
                    classObj.getPolitics(),
                    classObj.getHistory(),
                    classObj.getGeography(),
                    classObj.getUpdateTime(), 
                    id);
            
            // 设置ID
            classObj.setId(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            
            // 构建返回的班级数据，使字段名与前端期望一致
            // 查询更新后的最新班级数据
            String classSql = "SELECT id, class_name as className, grade as gradeLevel, " +
                             "IFNULL(chinese, '待分配') as chineseTeacher, " +
                             "IFNULL(math, '待分配') as mathTeacher, " +
                             "IFNULL(english, '待分配') as englishTeacher, " +
                             "IFNULL(physics, '待分配') as physicsTeacher, " +
                             "IFNULL(chemistry, '待分配') as chemistryTeacher, " +
                             "IFNULL(biology, '待分配') as biologyTeacher, " +
                             "IFNULL(politics, '待分配') as politicsTeacher, " +
                             "IFNULL(history, '待分配') as historyTeacher, " +
                             "IFNULL(geography, '待分配') as geographyTeacher " +
                             "FROM classes WHERE id = ?";
            List<Map<String, Object>> classResults = jdbcTemplate.queryForList(classSql, id);
            Map<String, Object> classData = classResults.get(0);
            
            // 查询班级中的学生数量
            String countSql = "SELECT COUNT(*) FROM students WHERE class_name = (SELECT class_name FROM classes WHERE id = ?)";
            Integer studentCount = jdbcTemplate.queryForObject(countSql, Integer.class, id);
            classData.put("studentCount", studentCount != null ? studentCount : 0);
            
            result.put("data", classData);
            result.put("message", "班级更新成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("更新班级失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新班级失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 删除班级
     */
    @DeleteMapping("/class/{id}")
    public ResponseEntity<?> deleteClass(@PathVariable Long id) {
        try {
            logger.info("删除班级: id={}", id);
            
            // 检查班级是否存在
            String checkExistsSql = "SELECT COUNT(*) FROM classes WHERE id = ?";
            Integer existsCount = jdbcTemplate.queryForObject(checkExistsSql, Integer.class, id);
            
            if (existsCount == null || existsCount == 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的班级");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 检查班级是否有关联的学生
            String checkStudentsSql = "SELECT COUNT(*) FROM students WHERE class_name = (SELECT class_name FROM classes WHERE id = ?)";
            Integer studentCount = jdbcTemplate.queryForObject(checkStudentsSql, Integer.class, id);
            
            if (studentCount != null && studentCount > 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "班级中存在学生，无法删除");
                return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
            }
            
            // 删除班级
            String deleteSql = "DELETE FROM classes WHERE id = ?";
            jdbcTemplate.update(deleteSql, id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "班级删除成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除班级失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "删除班级失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 获取班级学生列表
     */
    @GetMapping("/class/{id}/students")
    public ResponseEntity<?> getStudentsByClassId(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("获取班级学生列表: classId={}, page={}, size={}", id, page, size);
            
            // 检查班级是否存在
            String checkExistsSql = "SELECT COUNT(*) FROM classes WHERE id = ?";
            Integer existsCount = jdbcTemplate.queryForObject(checkExistsSql, Integer.class, id);
            
            if (existsCount == null || existsCount == 0) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未找到ID为 " + id + " 的班级");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 先获取班级名称
            String classNameSql = "SELECT class_name FROM classes WHERE id = ?";
            String className = jdbcTemplate.queryForObject(classNameSql, String.class, id);
            
            // 获取班级中的所有学生（通过班级名称）
            List<Student> students = studentService.findByClassName(className);
            int totalStudents = students.size();
            
            // 手动分页 (简化处理)
            int fromIndex = (page - 1) * size;
            int toIndex = Math.min(fromIndex + size, students.size());
            
            if (fromIndex < students.size()) {
                students = students.subList(fromIndex, toIndex);
            } else {
                students = new ArrayList<>();
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", students);
            result.put("total", totalStudents);
            result.put("page", page);
            result.put("size", size);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取班级学生列表失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取班级学生列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 批量重置教师密码
     */
    @PostMapping("/teachers/reset-password")
    public ResponseEntity<?> resetTeachersPassword(@RequestBody Map<String, Object> requestBody) {
        try {
            List<?> teacherIdObjects = (List<?>) requestBody.get("teacherIds");
            String password = requestBody.get("password") != null ? requestBody.get("password").toString() : null;
            
            if (teacherIdObjects == null || teacherIdObjects.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未选择教师");
                return ResponseEntity.badRequest().body(result);
            }
            
            logger.info("重置教师密码: teacherIds={}, 使用{}密码", teacherIdObjects, password == null ? "默认" : "指定");
            
            // 如果未指定密码，使用默认密码
            if (password == null || password.isEmpty()) {
                password = defaultPassword;
            }
            
            int successCount = 0;
            for (Object idObject : teacherIdObjects) {
                try {
                    // 安全地将任何数字类型转换为Long
                    Long teacherId;
                    if (idObject instanceof Integer) {
                        teacherId = ((Integer) idObject).longValue();
                    } else if (idObject instanceof Long) {
                        teacherId = (Long) idObject;
                    } else if (idObject instanceof Number) {
                        teacherId = ((Number) idObject).longValue();
                    } else {
                        teacherId = Long.parseLong(idObject.toString());
                    }
                    
                    Optional<Teacher> teacherOpt = teacherService.getTeacherById(teacherId);
                    if (teacherOpt.isPresent()) {
                        Teacher teacher = teacherOpt.get();
                        teacher.setPassword(password);
                        teacherService.saveTeacher(teacher);
                        successCount++;
                    }
                } catch (Exception e) {
                    logger.error("重置教师[{}]密码失败: {}", idObject, e.getMessage());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            if (successCount == teacherIdObjects.size()) {
                result.put("success", true);
                result.put("message", "成功重置 " + successCount + " 名教师的密码");
            } else if (successCount > 0) {
                result.put("success", true);
                result.put("message", "部分重置成功: " + successCount + "/" + teacherIdObjects.size());
            } else {
                result.put("success", false);
                result.put("message", "重置密码失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("重置教师密码失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "重置密码失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 批量删除教师
     */
    @PostMapping("/teachers/batch-delete")
    public ResponseEntity<?> batchDeleteTeachers(@RequestBody Map<String, Object> requestBody) {
        try {
            List<?> teacherIdObjects = (List<?>) requestBody.get("teacherIds");
            
            if (teacherIdObjects == null || teacherIdObjects.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "未选择教师");
                return ResponseEntity.badRequest().body(result);
            }
            
            logger.info("批量删除教师: teacherIds={}", teacherIdObjects);
            
            int successCount = 0;
            for (Object idObject : teacherIdObjects) {
                try {
                    // 安全地将任何数字类型转换为Long
                    Long teacherId;
                    if (idObject instanceof Integer) {
                        teacherId = ((Integer) idObject).longValue();
                    } else if (idObject instanceof Long) {
                        teacherId = (Long) idObject;
                    } else if (idObject instanceof Number) {
                        teacherId = ((Number) idObject).longValue();
                    } else {
                        teacherId = Long.parseLong(idObject.toString());
                    }
                    
                    teacherService.deleteTeacher(teacherId);
                    successCount++;
                } catch (Exception e) {
                    logger.error("删除教师[{}]失败: {}", idObject, e.getMessage());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            if (successCount == teacherIdObjects.size()) {
                result.put("success", true);
                result.put("message", "成功删除 " + successCount + " 名教师");
            } else if (successCount > 0) {
                result.put("success", true);
                result.put("message", "部分删除成功: " + successCount + "/" + teacherIdObjects.size());
            } else {
                result.put("success", false);
                result.put("message", "删除失败");
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("批量删除教师失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 批量导入学生
     */
    @PostMapping("/students/batch-import")
    public ResponseEntity<?> batchImportStudents(@RequestBody List<Student> students) {
        try {
            logger.info("批量导入学生: 数量={}", students.size());
            
            List<Student> successList = new ArrayList<>();
            List<Map<String, Object>> failList = new ArrayList<>();
            
            for (Student student : students) {
                try {
                    // 检查学号是否已存在
                    String checkSql = "SELECT COUNT(*) FROM students WHERE student_id = ?";
                    Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, student.getStudentId());
                    
                    if (count != null && count > 0) {
                        Map<String, Object> failInfo = new HashMap<>();
                        failInfo.put("student", student);
                        failInfo.put("reason", "学生学号已存在");
                        failList.add(failInfo);
                        continue;
                    }
                    
                    // 设置默认密码
                    if (student.getPassword() == null || student.getPassword().isEmpty()) {
                        student.setPassword(defaultPassword);
                    }
                    
                    // 设置创建时间和更新时间
                    LocalDateTime now = LocalDateTime.now();
                    student.setCreateTime(now);
                    student.setUpdateTime(now);
                    
                    // 设置状态为启用
                    student.setStatus(1);
                    
                    // 保存学生
                    Student savedStudent = studentService.save(student);
                    successList.add(savedStudent);
                } catch (Exception e) {
                    logger.error("导入学生失败: {}", e.getMessage(), e);
                    Map<String, Object> failInfo = new HashMap<>();
                    failInfo.put("student", student);
                    failInfo.put("reason", "系统错误: " + e.getMessage());
                    failList.add(failInfo);
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("successCount", successList.size());
            result.put("failCount", failList.size());
            result.put("successList", successList);
            result.put("failList", failList);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("批量导入学生失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量导入学生失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取所有班级列表（不分页）
     */
    @GetMapping("/classes/all")
    public ResponseEntity<?> getAllClassesWithoutPagination() {
        try {
            logger.info("获取所有班级列表（不分页）");
            
            // 获取所有班级并统计每个班级的学生数量
            String sql = "SELECT c.id, c.class_name as className, c.grade as gradeLevel, " +
                         "COUNT(s.id) as studentCount, " +
                         "IFNULL(c.chinese, '待分配') as chineseTeacher, " +
                         "IFNULL(c.math, '待分配') as mathTeacher, " +
                         "IFNULL(c.english, '待分配') as englishTeacher, " +
                         "IFNULL(c.physics, '待分配') as physicsTeacher, " +
                         "IFNULL(c.chemistry, '待分配') as chemistryTeacher, " +
                         "IFNULL(c.biology, '待分配') as biologyTeacher, " +
                         "IFNULL(c.politics, '待分配') as politicsTeacher, " +
                         "IFNULL(c.history, '待分配') as historyTeacher, " +
                         "IFNULL(c.geography, '待分配') as geographyTeacher " +
                         "FROM classes c " +
                         "LEFT JOIN students s ON c.class_name = s.class_name " +
                         "GROUP BY c.id";
            List<Map<String, Object>> classes = jdbcTemplate.queryForList(sql);
            
            // 不再需要设置班号和班主任字段
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", classes);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取所有班级列表失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取所有班级列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 将英文学科代码转换为中文学科名称
     */
    private String convertSubjectCodeToChinese(String subjectCode) {
        if (subjectCode == null) return "";
        
        switch (subjectCode.toLowerCase()) {
            case "chinese": return "语文";
            case "math": return "数学";
            case "english": return "英语";
            case "physics": return "物理";
            case "chemistry": return "化学";
            case "biology": return "生物";
            case "politics": return "政治";
            case "history": return "历史";
            case "geography": return "地理";
            default: return subjectCode; // 如果没有匹配，返回原始代码
        }
    }

    /**
     * 将中文学科名称转换为英文代码
     */
    private String convertSubjectToCode(String subjectName) {
        if (subjectName == null) return "";
        
        switch (subjectName) {
            case "语文": return "chinese";
            case "数学": return "math";
            case "英语": return "english";
            case "物理": return "physics";
            case "化学": return "chemistry";
            case "生物": return "biology";
            case "政治": return "politics";
            case "历史": return "history";
            case "地理": return "geography";
            default: 
                // 如果已经是英文代码，则直接返回
                if (isEnglishSubjectCode(subjectName)) {
                    return subjectName.toLowerCase();
                }
                // 否则返回原值
                return subjectName;
        }
    }
    
    /**
     * 判断是否已经是英文学科代码
     */
    private boolean isEnglishSubjectCode(String subject) {
        if (subject == null) return false;
        String lowerSubject = subject.toLowerCase();
        return lowerSubject.equals("chinese") || lowerSubject.equals("math") || 
               lowerSubject.equals("english") || lowerSubject.equals("physics") || 
               lowerSubject.equals("chemistry") || lowerSubject.equals("biology") || 
               lowerSubject.equals("politics") || lowerSubject.equals("history") || 
               lowerSubject.equals("geography");
    }
} 